package com.example.demo.controller;

import com.example.demo.pojo.Account;
import com.example.demo.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/account")
public class AccountController {
    private static final String ERROR_MESSAGES = "errorMessages";

    @Autowired
    private AccountService accountService;

    @RequestMapping("/saveAccount")
    public String addAccount(Account account, boolean conditions, Model model) {

        if (!conditions) {
            String msg = "请确认注册条款";
            model.addAttribute(ERROR_MESSAGES, msg);
            return "/sign-up";
        }
        boolean addAccount = accountService.addAccount(account);
        if (addAccount) {
            return "redirect:/login";
        } else {
            String msg = "用户名已注册，请重新输入";
            model.addAttribute(ERROR_MESSAGES, msg);
            return "/sign-up";
        }
    }

    @RequestMapping("/toReset")
    public String toResetPass(String username, String email, Model model) {

        boolean b = accountService.searchAccountByUserNameAndEmail(username, email);
        if (!b) {
            String msg = "用户名或邮箱不存在";
            model.addAttribute(ERROR_MESSAGES, msg);
            return "/reset-password-send-email";
        }
        model.addAttribute("username", username);
        return "/reset-password";
    }

    @RequestMapping("/toSend")
    public String toSendEmail() {

        return "/reset-password-send-email";
    }

    @RequestMapping("/resetPass")
    public String resetPassword(String password, String username) {

        accountService.updatePasswordByUserName(password, username);
        return "/sign-in";
    }
}
